package cc.yiueil.filter;

import cc.yiueil.entity.UserEntity;
import cc.yiueil.utils.JwtUtils;
import cc.yiueil.vo.ResultVo;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter extends OncePerRequestFilter {
    @Autowired
    ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        String requestURI = request.getRequestURI();
        // 非登录接口, 验证是否携带JWT
        if (requestURI.contains("/login")) {
            filterChain.doFilter(request, response);
            return;
        }
        String jwtToken = request.getHeader("jwt-token");
        if (!StringUtils.hasText(jwtToken)) {
            response.getWriter().write(objectMapper.writeValueAsString(ResultVo.error(403, "未登录！")));
            return;
        }
        if (JwtUtils.validateToken(jwtToken)) {
            DecodedJWT decodedJWT = JwtUtils.decodedJWT(jwtToken);
            String userEntityString = decodedJWT.getClaim("user").asString();
            UserEntity userEntity = objectMapper.readValue(userEntityString, UserEntity.class);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userEntity, null, userEntity.getAuthorities()));
            doFilter(request, response, filterChain);
            return;
        }
        response.getWriter().write(objectMapper.writeValueAsString(ResultVo.error(403, "未授权或授权到期！")));
    }
}
